package com.buobao.jdbc.demo;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

/**
 * 一个简单的事务提交的示例
 * 这里一个connection相当于一个会话，当开启手动提交后，只有在调用commit后才会真正提交数据
 */
public class TransactionSample {
    public static void main(String[] arg) {
        Connection connection=null;
        PreparedStatement statement = null;

        try {
            long starttime = System.currentTimeMillis();

            connection = DbUtil.getConnection();
            String sql = "insert into employee(eno,ename,salary,dname,hiredate) values (?,?,?,?,?)";
            connection.setAutoCommit(false); //设置事务手动提交
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i=0;i<200000;i++) {
                statement = connection.prepareStatement(sql);
                statement.setInt(1,i);
                statement.setString(2,"name"+i);
                statement.setFloat(3,i*100.0f);
                statement.setString(4,"研发部");
                //statement.setDate(5,new Date(System.currentTimeMillis()));
                statement.setString(5,format.format(new java.util.Date()));
                int result = statement.executeUpdate();
//                if (result!=0) {
//                    System.out.println("insert success "+i);
//                }
            }
            connection.commit(); //运行到这里数据才会提交
            System.out.println("runtime:"+(System.currentTimeMillis()-starttime));
        } catch (ClassNotFoundException e) {
            try {
                connection.rollback(); //异常则回滚
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } finally {
            try {
                DbUtil.closeConnection(null,statement,connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
